
package com.campus.server.service;

import com.campus.common.message.*;
import com.campus.common.vo.*;
import com.campus.server.dao.CourseDao;


import java.util.*;

public class CourseService {

    private final CourseDao courseDao = new CourseDao();

    // 处理请求
    public StudentCourseResponse handle(StudentCourseRequest req) {
        switch (req.getAction()) {
            case VIEW_AVAILABLE_COURSES:
                List<Course> avaliablefirstCourses = courseDao.getFirstTimeCourses(req.getStudentId());
                List<Course> avaliableretakeCourses = courseDao.getRetakeCourses(req.getStudentId());

                // 合并两个列表
                List<Course> availableCourses = new ArrayList<>();
                availableCourses.addAll(avaliablefirstCourses);
                availableCourses.addAll(avaliableretakeCourses);

                return new StudentCourseResponse(true, "获取可选课程成功", availableCourses, true);
            case VIEW_ALL_COURSES:
                List<Course> allCourses = courseDao.getAllCourses();
                return new StudentCourseResponse(true, "获取已选课程成功", allCourses, true);
            case VIEW_SELECTED_COURSES:
                List<Course> selectedCourses = courseDao.getSelectedCourses(req.getStudentId());
                System.out.println("已选课程数目 = " + selectedCourses.size());
                return new StudentCourseResponse(true, "获取已选课程成功", selectedCourses, true);

            case VIEW_FIRST_TIME_COURSES:
                List<Course> firstCourses = courseDao.getFirstTimeCourses(req.getStudentId());
                return new StudentCourseResponse(true, "获取首修课程成功", firstCourses, true);

            case VIEW_RETAKE_COURSES:
                List<Course> retakeCourses = courseDao.getRetakeCourses(req.getStudentId());
                return new StudentCourseResponse(true, "获取重修课程成功", retakeCourses, true
                );

            case SELECT_CLASSROOM:
                return selectClassroom(req.getStudentId(), req.getClassId());

            case DROP_CLASSROOM:
                return dropClassroom(req.getStudentId(), req.getClassId());
            case QUERY_COURSE:
                // 统一用一个 keyword 搜索（支持课程ID 和 课程名称）
                String keyword = req.getKeyword();
                if (keyword == null || keyword.trim().isEmpty()) {
                    keyword = req.getCourseName();
                }

                List<Course> courses = courseDao.queryCourse(keyword);

                if (courses != null && !courses.isEmpty()) {
                    System.out.println("找到 " + courses.size() + " 个匹配的课程");
                    return new StudentCourseResponse(true, "查询课程成功", courses, true
                    );
                }
                else
                {
                    System.out.println("未找到匹配的课程");
                    return new StudentCourseResponse(false, "未找到匹配的课程", (Course) null);
                }

            default:
                return new StudentCourseResponse(false, "未知请求", (Course) null);

        }
    }

    // 选班逻辑
    private StudentCourseResponse selectClassroom(String studentId, String classId) {
        Classroom target = courseDao.getClassById(classId);
        if (target == null) {
            return new StudentCourseResponse(false, "教学班不存在", (Classroom) null);
        }

        // 1. 已选过该课程
        if (courseDao.hasSelected(studentId, target.getCourseId())) {
            return new StudentCourseResponse(false, "您已选择该课程", (Classroom) null);
        }

        // 2. 已修过该课程
        Integer score = courseDao.getScore(studentId, target.getCourseId());
        if (score != null) {
            if (score >= 60) {
                return new StudentCourseResponse(false, "您已修过该课程并通过，不能重复选修", (Classroom) null);
            } else {
                if (!"重修".equalsIgnoreCase(target.getClassType())) {
                    return new StudentCourseResponse(false, "重修课程必须选择重修班", (Classroom) null);
                }
                System.out.println("学生 " + studentId + " 正在重修课程 " + target.getCourseId());
            }
        } else {
            if (!"首修".equalsIgnoreCase(target.getClassType())) {
                return new StudentCourseResponse(false, "首修课程必须选择首修班", (Classroom) null);
            }
        }

        // 3. 时间冲突检查
        List<Classroom> selected = courseDao.getSelectedClassroomsFlat(studentId);
        for (Classroom c : selected) {
            if (c.getCourseTime().equals(target.getCourseTime())) {
                return new StudentCourseResponse(false,
                        "选班失败：时间冲突（与《" + c.getCourseId() + "》）", (Classroom) null);
            }
        }

        // 4. 容量检查
        if (target.getSelectedCount() >= target.getCapacity()) {
            return new StudentCourseResponse(false, "选班失败：班级容量已满", (Classroom) null);
        }

        // 5. 插入记录（含更新人数）000
        boolean success = courseDao.insertStudentClassroomSafely(studentId, classId);
        if (success) {
            return new StudentCourseResponse(true, "选班成功", target);
        } else {
            return new StudentCourseResponse(false, "选班失败：数据库错误", (Classroom) null);
        }
    }


    // 退班逻辑
    private StudentCourseResponse dropClassroom(String studentId, String classId) {
        Classroom target = courseDao.getClassById(classId);
        if (target == null) return new StudentCourseResponse(false, "班级不存在", (Classroom) null);

        // 判断是否选过
        List<Classroom> selected = courseDao.getSelectedClassroomsFlat(studentId);
        boolean hasClass = selected.stream().anyMatch(c -> c.getClassId().equals(classId));
        if (!hasClass) return new StudentCourseResponse(false, "您未选择该班级", (Classroom) null);

        boolean deleted = courseDao.deleteStudentClassroom(studentId, classId);
        if (deleted) return new StudentCourseResponse(true, "退班成功", target);
        return new StudentCourseResponse(false, "退班失败：数据库操作错误", (Classroom) null);
    }


    public TeacherCourseResponse handle(TeacherCourseRequest req) {
        switch (req.getAction()) {
            // 查看所有课程（带班级信息）
            case VIEW_ALL_COURSES:
                List<Course> allCourses = courseDao.getAllCourses();
                if (allCourses != null && !allCourses.isEmpty()) {
                    return new TeacherCourseResponse(true, "获取所有课程成功", allCourses, true);
                } else {
                    return new TeacherCourseResponse(false, "没有找到课程", (List<Course>) null, true);
                }

                // 查看教师教授的课程
            case VIEW_TEACHING_COURSES:
                List<Course> teachingCourses = courseDao.getCoursesByTeacher(req.getTeacherId());
                if (teachingCourses != null && !teachingCourses.isEmpty()) {
                    return new TeacherCourseResponse(true, "获取教授课程成功", teachingCourses, true);
                } else {
                    return new TeacherCourseResponse(false, "该教师没有教授课程", (List<Course>) null, true);
                }

            case QUERY_COURSE:
                // 统一用一个 keyword 搜索（支持课程ID 和 课程名称）
                String keyword = req.getKeyword();
                if (keyword == null || keyword.trim().isEmpty()) {
                    keyword = req.getCourseName();
                }

                List<Course> courses = courseDao.queryCourse(keyword);

                if (courses != null && !courses.isEmpty()) {
                    System.out.println("找到 " + courses.size() + " 个匹配的课程");
                    return new TeacherCourseResponse(true, "查询课程成功", courses, true);
                }
                else
                {
                    System.out.println("未找到匹配的课程");
                    return new TeacherCourseResponse(false, "未找到匹配的课程", (Course) null);
                }

                // 查看某个班级的学生名单
            case VIEW_STUDENTS_IN_CLASS:
                List<Student> students = courseDao.getStudentsByClassId(req.getClassId());
                if (students != null && !students.isEmpty()) {
                    return new TeacherCourseResponse(true, "获取学生名单成功", students);
                } else {
                    return new TeacherCourseResponse(false, "该班级暂无学生", (List<Student>) null);
                }

                // 默认
            default:
                return new TeacherCourseResponse(false, "未知请求", (Course) null);
        }
    }
    // ---------------- 管理员端 ----------------
    public AdminCourseResponse handle(AdminCourseRequest req)
    {
        switch
        (req.getAction()) {
            case VIEW_ALL_COURSES:
                List<Course> allCourses = courseDao.getAllCourses();
                return new AdminCourseResponse(true, "获取所有课程成功", allCourses);

            case QUERY_COURSE:
                // 统一用一个 keyword 搜索（支持课程ID 和 课程名称）
                String keyword = req.getKeyword();
                if (keyword == null || keyword.trim().isEmpty()) {
                    keyword = req.getCourseName();
                }

                List<Course> courses = courseDao.queryCourse(keyword);

                if (courses != null && !courses.isEmpty()) {
                    System.out.println("找到 " + courses.size() + " 个匹配的课程");
                    return new AdminCourseResponse(true, "查询课程成功", courses);
                }
                else
                {
                    System.out.println("未找到匹配的课程");
                    return new AdminCourseResponse(false, "未找到匹配的课程", (Course) null);
                }

            case UPDATE_COURSE:
                // 1. 获取原课程信息
                Course oldCourse = courseDao.getCourseById(req.getCourseId());
                if (oldCourse == null) {
                    return new AdminCourseResponse(false, "课程不存在", (Course) null);
                }

                String courseId   = oldCourse.getCourseId();
                String oldName    = oldCourse.getCourseName();
                int oldCredit     = oldCourse.getCredit();
                String oldDept    = oldCourse.getDepartment();   // ✅ 原开课学院

                String newName    = req.getCourseName();
                int newCredit     = req.getCredit();
                String newDept    = req.getDepartment();         // ✅ 新开课学院

                // 2. 检查是否有改动
                if (oldName.equals(newName) && oldCredit == newCredit && oldDept.equals(newDept)) {
                    return new AdminCourseResponse(false, "未修改任何内容", (Course) null);
                }

                // 3. 更新课程信息（名称、学分、开课学院）
                boolean updated = courseDao.updateCourseById(courseId, newName, newCredit, newDept);
                if (updated) {
                    return new AdminCourseResponse(true, "课程信息修改成功", (Course) null);
                } else {
                    return new AdminCourseResponse(false, "课程信息修改失败", (Course) null);
                }

            case DELETE_COURSE:   // ✅ 新增删除课程逻辑
                boolean deletedCourse = courseDao.deleteCourse(req.getCourseId());
                if (deletedCourse) {
                    return new AdminCourseResponse(true, "删除课程成功", (Course) null);
                }
                else
                {
                    return new AdminCourseResponse(false, "删除课程失败，课程可能不存在", (Course) null);
                }


            case ADD_CLASSROOM:
                boolean added = courseDao.addClassroom(req.getClassroom());
                if (added) {
                    return new AdminCourseResponse(true, "新增班级成功", req.getClassroom());
                }
                else
                {
                    return new AdminCourseResponse(false, "新增班级失败", (Classroom) null);
                }

            case DELETE_CLASSROOM:
                boolean deleted = courseDao.deleteClassroom(req.getClassId());
                if (deleted) {
                    return new AdminCourseResponse(true, "删除班级成功", (Classroom) null);
                }
                else
                {
                    return new AdminCourseResponse(false, "删除班级失败", (Classroom) null);
                }

            case UPDATE_CLASSROOM:
                boolean classUpdated = courseDao.updateClassroom(req.getClassroom());
                if (classUpdated) {
                    return new AdminCourseResponse(true, "班级信息修改成功", req.getClassroom());
                }
                else
                {
                    return new AdminCourseResponse(false, "班级信息修改失败", (Classroom) null);
                }

            case ADD_STUDENT_TO_CLASS:
                boolean stuAdded = courseDao.addStudentToClass(req.getClassId(), req.getStudentId());
                if (stuAdded) {
                    return new AdminCourseResponse(true, "添加学生成功", (Student) null);
                }
                else
                {
                    return new AdminCourseResponse(false, "添加学生失败", (Student) null);
                }

            case REMOVE_STUDENT_FROM_CLASS:
                boolean stuRemoved = courseDao.removeStudentFromClass(req.getClassId(), req.getStudentId());
                if (stuRemoved) {
                    return new AdminCourseResponse(true, "移除学生成功", (Student) null);
                }
                else
                {
                    return new AdminCourseResponse(false, "移除学生失败", (Student) null);
                }
                // 查看某个班级的学生名单
            case VIEW_STUDENTS_IN_CLASS:
                List<Student> students = courseDao.getStudentsByClassId(req.getClassId());
                if (students != null && !students.isEmpty()) {
                    return new AdminCourseResponse(true, "获取学生名单成功", students);
                } else {
                    return new AdminCourseResponse(false, "该班级暂无学生", (List<Student>) null);
                }
                // ✅ 新增：获取所有老师
            case VIEW_ALL_TEACHERS:
                List<Teacher> teachers = courseDao.getAllTeachers();
                if (teachers != null && !teachers.isEmpty()) {
                    return new AdminCourseResponse(true, "获取所有教师成功", teachers);
                } else {
                    return new AdminCourseResponse(false, "没有找到教师", (List<Teacher>) null);
                }
            case ADD_COURSE:
                Course newCourse = new Course();
                newCourse.setCourseId(req.getCourseId());
                newCourse.setCourseName(req.getCourseName());
                newCourse.setCredit(req.getCredit());
                newCourse.setDepartment(req.getDepartment());

                boolean inserted = courseDao.addCourse(newCourse);
                if (inserted) {
                    return new AdminCourseResponse(true, "新增课程成功", newCourse);
                }
                else
                {
                    return new AdminCourseResponse(false, "新增课程失败", (Course) null);
                }

            default:
                return new AdminCourseResponse(false, "未知请求", (Course) null);
        }
    }

}